package com.fcscs.cservice.client.main.configuration.reservation;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.fcscs.core.common.authority.CServiceAuthority;
import com.fcscs.core.common.authority.UserAuthority;
import com.fcscs.core.domain.IdNameModel;
import com.fcscs.core.domain.Property;
import com.fcscs.core.gwt.common.AsyncCallbackListener;
import com.fcscs.core.gwt.common.CoreConstants;
import com.fcscs.core.gwt.common.CoreEnums.SubmitType;
import com.fcscs.core.gwt.common.FormSubmitListener;
import com.fcscs.core.gwt.common.SessionContext;
import com.fcscs.core.gwt.common.ui.FcsFields.EasyClearCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.FormButton;
import com.fcscs.core.gwt.common.ui.CenteredInfo;
import com.fcscs.core.gwt.common.ui.FcsFormPanel;
import com.fcscs.core.gwt.common.ui.FcsPanel;
import com.fcscs.cservice.client.common.CServiceConstants;
import com.fcscs.cservice.client.common.TextFieldAndIconButtonField;
import com.fcscs.cservice.client.common.TextFieldAndIconButtonField.TextFieldListener;
import com.fcscs.cservice.client.common.controller.CServiceCommonServiceController;
import com.fcscs.cservice.client.common.model.configuration.reservation.LanguageDomainModelData;
import com.fcscs.cservice.client.common.model.configuration.reservation.PropertyIdNameModelData;
import com.fcscs.cservice.domain.Language;
import com.fcscs.share.gwt.common.ShareGWTConstants;
import com.google.gwt.user.client.ui.Widget;

public class LanguageAdminPanel extends FcsPanel implements
		FormSubmitListener<Language> {
	private VerticalPanel vp;
	private EasyClearCombobox<PropertyIdNameModelData> propCombox;
	private ListStore<PropertyIdNameModelData> propListStore;
	private TextFieldAndIconButtonField searchFieldBtn;
	private List<IdNameModel<Property>> propGroupIdNames;
	private LanguageGrid grid;
	private LanguageDialog dialog;
	private Long propId;
	private FormButton addButton;
	private Language language;
	
	public LanguageAdminPanel(String id) {
		super(id);
	}

	@Override
	public void init() {
		if(null == vp){
			vp = new VerticalPanel();
			vp.setId("LanguageAdminPanel_vpPanel");
			vp.setSpacing(5);
			
			HorizontalPanel hp = new HorizontalPanel();
			hp.setId("LanguageAdminPanel_hp");
			hp.setSpacing(5);
			
			Label propLabel = new Label(CoreConstants.CORE_CONSTANTS.property() + CoreConstants.REQURIED_FIELD_LABEL);
			propLabel.setId("LanguageAdminPanel_propLabel");
			propLabel.setWidth(150);
			
			propListStore = new ListStore<PropertyIdNameModelData>();
			propCombox = new EasyClearCombobox<PropertyIdNameModelData>();
			propCombox.setId("LanguageAdminPanel_propCombox");
//			propCombox.setFieldLabel(CoreConstants.CORE_CONSTANTS.property());
			propCombox.setWidth(200);
			propCombox.setDisplayField(CoreConstants.FULLTNAME);
			propCombox.setAllowBlank(false);
			propCombox.setForceSelection(true);
			propCombox.setTriggerAction(TriggerAction.ALL);
			propCombox.setStore(propListStore);
			propCombox.addSelectionChangedListener(new SelectionChangedListener<PropertyIdNameModelData>() {
				
				@Override
				public void selectionChanged(SelectionChangedEvent<PropertyIdNameModelData> se) {
					PropertyIdNameModelData pinmmd = propCombox.getValue();
					if (pinmmd != null) {
						propId = pinmmd.getEntity().getId();
						grid.setCurrentProperty(pinmmd);
						searchFieldBtn.getTextField().clear();
						searchLanguage();
					}
				}
			});
			
			hp.add(propLabel);
			hp.add(propCombox);
			
//			Label l = new Label(CoreConstants.CORE_CONSTANTS.search() + CServiceConstants.FIELD_SEP);
//			hp.add(l);
			
			searchFieldBtn = new TextFieldAndIconButtonField(new TextFieldListener() {
				
				@Override
				public void onTextFieldEnterKeyPressSearch(String value) {
					if(value == null || value.trim().isEmpty()){
//						newSearch(true);
						searchLanguage();
					}else{
//						newSearch(false);
						searchLanguage();
					}
				}
				
				@Override
				public void onIconButtoSearch(String value) {
					
					if(value == null || value.trim().isEmpty()){
//						newSearch(true);
						searchLanguage();
					}else{
//						newSearch(false);
						searchLanguage();
					}
				}
			});
			searchFieldBtn.setId("LanguageAdminPanel_searchFieldBtn");
			searchFieldBtn.setStyleAttribute(CServiceConstants.CSS_MARGINLEFT, "13px");
			searchFieldBtn.getHicButton().setTitle(ShareGWTConstants.SHARE_GWT_MESSAGES.searchBy(
					CoreConstants.CORE_CONSTANTS.name()+ShareGWTConstants.SHARE_GWT_CONSTANTS.and()+CoreConstants.CORE_CONSTANTS.secondaryName()));
//			hp.add(searchFieldBtn);
			
			vp.add(hp);
			
			grid = LanguageGrid.getInstance(CServiceConstants.CSERVICE_CONSTANTS.guestLanguage(), null);
			grid.setId("LanguageAdminPanel_grid");
			vp.add(grid);
			
			addButton = new FormButton(CoreConstants.CORE_MESSAGES.
			    	operation(CoreConstants.CORE_CONSTANTS.add(),CServiceConstants.CSERVICE_CONSTANTS.guestLanguage()));
			addButton.setId("LanguageAdminPanel_addButton");
			addButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
			    @Override
			    public void componentSelected(ButtonEvent ce) {
			    	showAddLanguageDialog();
			    }
		    });
			vp.add(addButton);
			
			add(vp);
		}
		
		onShow();
	}

	@Override
	public UserAuthority getRequiredAuthority() {
		return CServiceAuthority.cSERVICE_CONFIG;
	}

	@Override
	protected Widget getViewPanel() {
		return vp;
	}

	@Override
	public void onShow() {
		loadProperty();
	}

	@Override
	public boolean onHide() {
		return true;
	}

	@Override
	public void formSubmitCallBack(FcsFormPanel<Language> form,
			SubmitType submitType) {
		dialog.getFormPanel().populateEntity(language);
		saveLanguage(language);
	}

	private void loadProperty() {
		propGroupIdNames = SessionContext.getInstance().getPropertyGroup();
		propListStore.removeAll();
		if (0 != propGroupIdNames.size()) {
			int propIndex = 0;
			for (IdNameModel<Property> inm : propGroupIdNames) {
				propListStore.add(new PropertyIdNameModelData(inm));
				if (propIndex == 0) {
					if (SessionContext.getInstance().getPropertyId() == inm.getId()) {
						propIndex = propListStore.getCount() - 1;
					}
				}
			}
			propCombox.setValue(propListStore.getAt(propIndex));
		} else {
			IdNameModel<Property> tempINM = new IdNameModel<Property>(SessionContext.getInstance().getPropertyId(), SessionContext.getInstance().getPropertyName());
			propListStore.add(new PropertyIdNameModelData(tempINM));
			propCombox.setValue(propListStore.getAt(0));
		}
//		propListStore.removeAll();
//		IdNameModel<Property> tempINM = new IdNameModel<Property>(SessionContext.getInstance().getPropertyId(), SessionContext.getInstance().getPropertyName());
//		propListStore.add(new PropertyIdNameModelData(tempINM));
//		propCombox.setValue(propListStore.getAt(0));
//		grid.setCurrentProperty(propListStore.getAt(0));
	}
	
	private void searchLanguage(){
		CServiceCommonServiceController.getINSTANCE().getLanguageList(
			propId, new AsyncCallbackListener<List<Language>>(){
				@Override
				public void onLogin(String username) {
					CServiceCommonServiceController.getINSTANCE().getLanguageList(
							propId,this);
				}

				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
							CoreConstants.CORE_CONSTANTS.systemError(), null);
				}

				@Override
				public void onSuccess(List<Language> result) {
					if(result != null){
						grid.removeAllModels();
						List<LanguageDomainModelData> modelDatas = new ArrayList<LanguageDomainModelData>();
						for (Language tmd : result) {
							modelDatas.add(new LanguageDomainModelData(tmd));
						}
						grid.addModels(modelDatas);
					}
				}
				
			});
	}
	
	private void showAddLanguageDialog(){
		language = new Language();
		dialog=LanguageDialog.getInstance(this, true, propCombox.getValue());
		dialog.getFormPanel().updateForm(language);
		dialog.show();
	}
	
	private void saveLanguage(final Language language){
		CServiceCommonServiceController.getINSTANCE().saveLanguage(
			language, new AsyncCallbackListener<Language>(){
				@Override
				public void onLogin(String username) {
					CServiceCommonServiceController.getINSTANCE().saveLanguage(
							language,this);
				}
				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
							CoreConstants.CORE_CONSTANTS.systemError(), null);
				}
				@Override
				public void onSuccess(Language result) {
					if(null != result){
					    grid.addModel(new LanguageDomainModelData(result));
					    dialog.hide();
					
					    CenteredInfo.displayCompleted(CoreConstants.CORE_CONSTANTS.added());
					}
				}
			});
	}
}
